package online.hxstart.code.leetcode;

import java.math.BigInteger;
import java.util.StringJoiner;

/**
 * @author huxing
 * @date 19-4-4 星期四 下午5:32
 * @describe
 */
public class AddTwoNumbers {

  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    StringBuilder a = new StringBuilder();
    get(l1, a);
    StringBuilder b = new StringBuilder();
    get(l2, b);
    String aa = new BigInteger(a.toString()).add(new BigInteger(b.toString())).toString();
    char[] chars = aa.toCharArray();
    return set(chars, chars.length - 1);
  }

  public ListNode addTwoNumbers(ListNode l1, ListNode l2, int data) {
    if (l1 != null && l2 != null) {
      int a = l1.val + l2.val + data;
      ListNode node;
      if (a < 10) {
        node = new ListNode(a);
        node.next = addTwoNumbers(l1.next, l2.next, 0);
      } else {
        node = new ListNode(a - 10);
        node.next = addTwoNumbers(l1.next, l2.next, 1);
      }
      return node;
    } else if (l1 != null) {
      int a = l1.val + data;
      if (a < 10) {
        l1.val = a;
      } else {
        l1.val = a - 10;
        l1.next = addTwoNumbers(l1.next, null, 1);
      }
      return l1;
    } else if (l2 != null) {
      int a = l2.val + data;
      if (a < 10) {
        l2.val = a;
      } else {
        l2.val = a - 10;
        l2.next = addTwoNumbers(null, l2.next, 1);
      }
      return l2;
    } else {
      if (data > 0) {
        return new ListNode(data);
      }
    }
    return null;
  }

  public void get(ListNode l, StringBuilder a) {
    a.insert(0, l.val);
    if (l.next != null) {
      get(l.next, a);
    }
  }

  public ListNode set(char[] chars, int i) {
    ListNode node;
    if (i > 0) {
      node = new ListNode(Integer.parseInt(String.valueOf(chars[i])));
      node.next = set(chars, i - 1);
      return node;
    } else {
      node = new ListNode(Integer.parseInt(String.valueOf(chars[i])));
      return node;
    }
  }

  public static void main(String[] args) {
    AddTwoNumbers a = new AddTwoNumbers();
    String a1 = "1234567";
    String a2 = "34567";
    System.out.println(
        a.addTwoNumbers(
            a.set(a1.toCharArray(), a1.length() - 1), a.set(a2.toCharArray(), a2.length() - 1)));
  }
}

class ListNode {
  int val;
  ListNode next;

  ListNode(int x) {
    val = x;
  }

  @Override
  public String toString() {
    return new StringJoiner(", ", ListNode.class.getSimpleName() + "[", "]")
        .add("val=" + val)
        .add("next=" + next)
        .toString();
  }
}
